<template>
  <ResponsiveLayout 
    layout="full" 
    :show-sidebar="false" 
    :safe-area="true"
    content-padding="0"
  >
    <div class="login-container" :class="{ 'mobile-layout': isMobile }">
      <div class="login-card" :class="{ 'mobile-card': isMobile }">
        <div class="login-header">
          <div class="logo-section">
            <OptimizedImage 
              src="/OIP.webp" 
              alt="小智医疗" 
              class="login-logo" 
              :lazy="false" 
              :width="isMobile ? 60 : 80" 
              :height="isMobile ? 60 : 80" 
            />
          </div>
          <h2 class="login-title">小智医疗助手</h2>
          <p class="login-subtitle">智能医疗，贴心服务</p>
        </div>
        
        <SecureForm
        ref="loginFormRef"
        :model-value="loginForm"
        :rules="loginRules"
        class="login-form"
        :show-submit-button="false"
        :show-reset-button="false"
        :enable-x-s-s-protection="true"
        :auto-sanitize="true"
        :prevent-duplicate-submit="true"
        :submit-delay="2000"
        @submit="handleSecureLogin"
        @update:model-value="updateLoginForm"
      >
        <template #default="{ formData }">
          <el-form-item prop="username">
            <el-input
              v-model="formData.username"
              placeholder="请输入用户名或手机号"
              prefix-icon="User"
              size="large"
              clearable
              maxlength="50"
              autocomplete="off"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              size="large"
              show-password
              clearable
              maxlength="100"
              autocomplete="new-password"
              @keyup.enter="() => loginFormRef.handleSubmit()"
            />
          </el-form-item>
          
          <el-form-item>
            <div class="login-options">
              <el-checkbox v-model="formData.rememberMe">
                记住我
              </el-checkbox>
              <el-link type="primary" :underline="false">
                忘记密码？
              </el-link>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-button"
              :loading="loading"
              @click="() => loginFormRef.handleSubmit()"
            >
              登录
            </el-button>
          </el-form-item>
          
          <el-form-item>
            <div class="register-link">
              <span>还没有账号？</span>
              <el-link type="primary" @click="$router.push('/register')">
                立即注册
              </el-link>
            </div>
          </el-form-item>
        </template>
      </SecureForm>
      
      <div class="quick-login">
        <el-divider>快速体验</el-divider>
        <div class="quick-buttons">
          <el-button
            type="info"
            plain
            size="large"
            class="demo-button"
            @click="handleDemoLogin"
          >
            游客体验
          </el-button>
          <el-button
            type="success"
            size="large"
            class="direct-access-button"
            @click="handleDirectAccess"
          >
            直接进入系统
          </el-button>
        </div>
      </div>
      </div>
    </div>
    
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="medical-icon medical-icon-1">🏥</div>
      <div class="medical-icon medical-icon-2">⚕️</div>
      <div class="medical-icon medical-icon-3">🩺</div>
      <div class="medical-icon medical-icon-4">💊</div>
    </div>
  </ResponsiveLayout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useResponsive } from '../utils/responsive'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import ResponsiveLayout from '../components/ResponsiveLayout.vue'
import SecureForm from '../components/SecureForm.vue'
import OptimizedImage from '../components/OptimizedImage.vue'
import { InputValidator } from '../utils/security'

const router = useRouter()
const userStore = useUserStore()
const { isMobile } = useResponsive()
const loginFormRef = ref()
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名或手机号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        const result = InputValidator.validateLength(value, 3, 50, '用户名')
        if (!result.valid) {
          callback(new Error(result.message))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        const result = InputValidator.validateLength(value, 6, 100, '密码')
        if (!result.valid) {
          callback(new Error(result.message))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 更新表单数据
const updateLoginForm = (newData) => {
  Object.assign(loginForm, newData)
}

// handleLogin函数已移除，所有登录逻辑通过handleSecureLogin处理

// 安全表单提交处理
const handleSecureLogin = async (sanitizedData) => {
  try {
    loading.value = true
    
    // 数据已经通过SecureForm处理，直接使用
    const loginData = {
      username: sanitizedData.username,
      password: sanitizedData.password,
      rememberMe: sanitizedData.rememberMe
    }
    
    // 检查密码是否为BCrypt格式（防止发送加密密码）
    if (loginData.password && loginData.password.startsWith('$2a$')) {
      ElMessage.error('检测到无效的密码格式，请清除浏览器自动填充后重新输入明文密码')
      return
    }
    
    // 额外的安全验证
    const usernameValidation = InputValidator.validateLength(loginData.username, 3, 50, '用户名')
    const passwordValidation = InputValidator.validateLength(loginData.password, 6, 100, '密码')
    
    if (!usernameValidation.valid) {
      ElMessage.error(usernameValidation.message)
      return
    }
    
    if (!passwordValidation.valid) {
      ElMessage.error(passwordValidation.message)
      return
    }
    
    console.log('安全登录数据:', loginData)
    console.log('密码长度:', loginData.password.length)
    console.log('密码格式检查:', loginData.password.startsWith('$2a$') ? 'BCrypt格式(错误)' : '明文格式(正确)')
    const result = await userStore.login(loginData)
    
    if (result.success) {
      ElMessage.success('登录成功！')
      router.push('/')
    } else {
      ElMessage.error(result.message || '登录失败，请检查用户名和密码')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleDemoLogin = async () => {
  try {
    loading.value = true
    
    // 使用预设的测试账号进行游客体验
    const result = await userStore.login({
      username: 'testuser',
      password: '123456'
    })
    
    if (result.success) {
      ElMessage.success('欢迎体验小智医疗版！')
      router.push('/')
    } else {
      ElMessage.error(result.message || '游客体验登录失败')
    }
  } catch (error) {
    console.error('游客体验登录错误:', error)
    ElMessage.error('游客体验功能暂时不可用，请使用账号登录')
  } finally {
    loading.value = false
  }
}

// 直接进入系统（无需登录）
const handleDirectAccess = () => {
  ElMessage.success('欢迎使用小智医疗系统！')
  router.push('/')
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.mobile-layout {
  padding: 16px;
  align-items: flex-start;
  padding-top: 60px;
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  width: 100%;
  max-width: 400px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
}

.mobile-card {
  padding: 24px;
  border-radius: 16px;
  max-width: 100%;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo-section {
  margin-bottom: 20px;
}

.login-logo {
  border-radius: 50%;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.login-logo:hover {
  transform: scale(1.05);
}

.login-title {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  transition: font-size 0.3s ease;
}

.login-subtitle {
  color: #7f8c8d;
  margin: 0;
  font-size: 16px;
  transition: font-size 0.3s ease;
}

.login-form {
  margin-top: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  background: linear-gradient(45deg, #409eff, #67c23a);
  border: none;
}

.login-button:hover {
  background: linear-gradient(45deg, #337ecc, #5daf34);
}

.register-link {
  text-align: center;
  width: 100%;
  color: #7f8c8d;
  font-size: 14px;
}

.quick-login {
  margin-top: 20px;
}

.quick-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.demo-button {
  width: 100%;
  height: 40px;
  border-radius: 8px;
}

.direct-access-button {
  width: 100%;
  height: 40px;
  border-radius: 8px;
  background: linear-gradient(45deg, #67c23a, #85ce61);
  border: none;
  font-weight: 600;
}

.direct-access-button:hover {
  background: linear-gradient(45deg, #5daf34, #73c142);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: -1;
}

.medical-icon {
  position: absolute;
  font-size: 60px;
  opacity: 0.1;
  animation: float 6s ease-in-out infinite;
}

.medical-icon-1 {
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.medical-icon-2 {
  top: 20%;
  right: 15%;
  animation-delay: 1.5s;
}

.medical-icon-3 {
  bottom: 30%;
  left: 15%;
  animation-delay: 3s;
}

.medical-icon-4 {
  bottom: 10%;
  right: 10%;
  animation-delay: 4.5s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(10deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    padding: 12px;
  }
  
  .mobile-layout {
    padding: 12px;
    padding-top: 40px;
  }
  
  .mobile-card {
    padding: 20px;
    border-radius: 12px;
  }
  
  .login-title {
    font-size: 24px;
  }
  
  .login-subtitle {
    font-size: 14px;
  }
  
  .medical-icon {
    display: none; /* 在移动端隐藏装饰图标 */
  }
}

@media (max-width: 480px) {
  .mobile-layout {
    padding: 8px;
    padding-top: 30px;
  }
  
  .mobile-card {
    padding: 16px;
  }
  
  .login-title {
    font-size: 20px;
  }
  
  .login-subtitle {
    font-size: 12px;
  }
}

/* 平板适配 */
@media (min-width: 769px) and (max-width: 1024px) {
  .login-card {
    max-width: 450px;
    padding: 36px;
  }
}

/* 横屏适配 */
@media (max-height: 600px) and (orientation: landscape) {
  .login-container {
    align-items: flex-start;
    padding-top: 20px;
  }
  
  .login-header {
    margin-bottom: 20px;
  }
  
  .medical-icon {
    display: none;
  }
}

/* 深色主题适配 */
@media (prefers-color-scheme: dark) {
  .login-card {
    background: rgba(30, 30, 30, 0.95);
  }
  
  .login-title {
    color: #ffffff;
  }
  
  .login-subtitle {
    color: #cccccc;
  }
}
</style>